const http = require('http');
const path = require('path');
const fse = require('fs-extra');
const controller = require('./controller')
// 开启服务
const app = http.createServer();
const port = 4000;
app.listen(port, () => {
    console.log(`Server start at http://127.0.0.1:${port}`);
})
// 监听
app.on('request', async (req, res) => {
    /* 允许跨域 */
    res.setHeader("Access-Control-Allow-Origin", '*');
    res.setHeader("Access-Control-Allow-Headers", '*');
    let { method, url } = req;
    method = method.toLowerCase();
    /* options请求 */
    if (method === "options") {
        res.end("ok")
    }
    /* post请求 */
    if (method === "post") {
        //单文件上传
        if (url === '/single') {
            controller.singleUpload(req, res);
        }
        //base64上传
        else if (url === '/single2') {
            controller.base64Upload(req, res);
        }
        //上传切片
        else if (url === '/chunk') {
            controller.chunkUpload(req, res);
        }
        //合并切片
        else if (url === '/merge') {
            controller.mergeUpload(req, res);
        }
        else {
            res.statusCode = 404;
            res.end(JSON.stringify({ msg: "路径不存在" }))
        }
    }
    /* get请求 */
    if (method === "get") {
        //静态目录
        if (url.startsWith("/static/")) {
            fse.readFile(path.join(__dirname, url), (err, data) => {
                if (err) {
                    redirect404(res, res);
                }
                res.end(data);
            })
        }
        else {
            redirect404(res, res);
        }
    }

})


// 404重定向
function redirect404(req, res) {
    res.statusCode = 302;
    res.setHeader('Location', '/static/404.html');
    res.end();
}
